package controllers

import (
	"autoPage/models"
	"encoding/json"
	"errors"
	"github.com/astaxie/beego"
	"strconv"
	"strings"
	"time"
)

// InterfacedefineController operations for Interfacedefine
type InterfacedefineController struct {
	BaseController
}

// URLMapping ...
func (c *InterfacedefineController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("Delete", c.Delete)
	c.Mapping("List", c.List)
	c.Mapping("Update", c.Update)
	c.Mapping("Edit", c.Edit)
	c.Mapping("Add", c.Add)
	c.Mapping("GetParams", c.GetParams)
}

// Post ...
// @Title Post
// @Description create Interfacedefine
// @Param	body		body 	models.Interfacedefine	true		"body for Interfacedefine content"
// @Success 201 {int} models.Interfacedefine
// @Failure 403 body is empty
// @router / [post]
func (c *InterfacedefineController) GetParams() {
	inter_id := c.GetString("interface_id")
	sms := DmsResStruct{Status: true, Msg: "", Data: ""}
	if inter_id == "" {
		sms.Msg = "no interface_id"
		c.ResReturn(sms)
	}
	interface_id, _ := strconv.ParseInt(inter_id, 10, 64)
	interfaceDefine, err := models.GetInterfacedefineById(interface_id)
	if err != nil {
		sms.Msg = err.Error()
		c.ResReturn(sms)
	}
	p := interfaceDefine.Params
	h := interfaceDefine.Headers
	paramtype := interfaceDefine.Paramtype
	data := map[string]string{"params": p, "headers": h, "paramtype": paramtype}
	sms.Data = data
	c.ResReturn(sms)
}

// Post ...
// @Title Post
// @Description create Interfacedefine
// @Param	body		body 	models.Interfacedefine	true		"body for Interfacedefine content"
// @Success 201 {int} models.Interfacedefine
// @Failure 403 body is empty
// @router / [post]
func (c *InterfacedefineController) Post() {
	var v models.Interfacedefine
	if err := c.ParseForm(&v); err != nil {
		//sic.Info(err)
		c.ShowMsg("添加失败", "/interfacedefine/list", 3)
	} else {
		if _, err := models.AddInterfacedefine(&v); err == nil {
			//sic.Info(&v)
			c.ShowMsg("添加成功", "/interfacedefine/list", 3)
		} else {
			//sic.Info(err)
			c.ShowMsg("添加失败", "/interfacedefine/list", 3)
		}
	}
}

// Update ...
// @Title Update
// @Description update the Skill
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Skill	true		"body for Skill content"
// @Success 200 {object} models.Skill
// @Failure 403 :id is not int
// @router /:id [Update]
func (sic *InterfacedefineController) Update() {
	var v models.Interfacedefine
	if err := sic.ParseForm(&v); err != nil {
		//sic.Info(err)
		sic.ShowMsg("保存失败", "/interfacedefine/list", 3)
	} else {
		//fmt.Println(&v)
		if err := models.UpdateInterfacedefineById(&v); err == nil {
			sic.ShowMsg("保存成功", "/interfacedefine/list", 3)
		} else {
			sic.ShowMsg("保存失败", "/interfacedefine/list", 3)
		}
	}
}

//编辑
func (sic *InterfacedefineController) Edit() {
	if sic.IsSubmit() {
		var e models.Interfacedefine
		// lang := sic.GetString("lang")
		// sic.Info(lang)
		if err := sic.ParseForm(&e); err != nil {
			sic.ShowMsg("接收表单失败，请重试!",   "-1", 4)
			beego.Error("failure to receive interfacedefine form edit", err.Error(), "")
		} else {

			e.Pubtime = time.Now().Format("2006-01-02 15:04:05")

			err := models.UpdateInterfacedefineById(&e)
			if err != nil {
				sic.ShowMsg("修改失败了",  "/interfacedefine/list", 3)
			} else {
				models.ClearInterfacedefineCacheById(e.Id) //清除权利缓存
				sic.ShowMsg("修改成功 ", "/interfacedefine/list", 3)
			}
		}
	} else {
		_, actionName := sic.GetControllerAndAction()
		sic.Data["ACTION_NAME"] = actionName
		var id int64
		mapp := sic.Ctx.Input.Params()
		id, _ = strconv.ParseInt(mapp["1"], 10, 64)

		data, _ := models.GetInterfacedefineById(id)
		sic.Data["Data"] = data
		sic.TplName = "interfacedefine/form.html"
	}
}

//添加
func (sic *InterfacedefineController) Add() {
	if sic.IsSubmit() {
		var e models.Interfacedefine

		if err := sic.ParseForm(&e); err != nil {
			sic.ShowMsg("接收表单失败，请重试!",  "-1", 4)
		} else {

			e.Pubtime = time.Now().Format("2006-01-02 15:04:05")

			_, err := models.AddInterfacedefine(&e)

			if err != nil {
				sic.ShowMsg("添加失败了",  "/interfacedefine/list", 3)
			} else {
				models.ClearInterfacedefineCacheById(e.Id)
				sic.ShowMsg("添加成功了",   "/interfacedefine/list", 3)
			}
		}
	} else {
		_, actionName := sic.GetControllerAndAction()
		sic.Data["ACTION_NAME"] = actionName
		sic.TplName = "interfacedefine/form.html"
	}
}

// GetOne ...
// @Title Get One
// @Description get Interfacedefine by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Interfacedefine
// @Failure 403 :id is empty
// @router /:id [get]
func (c *InterfacedefineController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	v, err := models.GetInterfacedefineById(id)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title List
// @Description get Interfacedefine
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Interfacedefine
// @Failure 403
// @router / [get]
func (c *InterfacedefineController) List() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	limit, _ := strconv.ParseInt(beego.AppConfig.String("pagesize"), 10, 64)
	var offset int64
	var page int64
	if v, err := c.GetInt64("p"); err == nil {
		page = v
		offset = (page - 1) * limit
	} else {
		page = 1
		offset = 0
	}
	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	name := c.GetString("name")
	lang := c.GetString("langs")
	q := make([]string, 0)
	if name != "" {
		q = append(q, `Name:`+name)
	}
	if lang != "" {
		q = append(q, `Lang:`+lang)
	}
	for _, cond := range q {
		kv := strings.SplitN(cond, ":", 2)
		if len(kv) != 2 {
			c.Data["json"] = errors.New("Error: invalid query key/value pair")
			c.ServeJSON()
			return
		}
		k, v := kv[0], kv[1]
		query[k] = v
	}
	sortby = append(sortby, "id")
	order = append(order, "desc")
	l, count, err := models.GetAllInterfacedefine(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["list"] = nil
	} else {
		c.Data["list"] = l
		if count > 1 {
			c.Data["Page"] = PageUtil(int(count), int(page), int(limit), l)
		}
	}
	c.Data["Name"] = name
	c.Data["Langs"] = lang
	c.Data["ActiveMenu"] = "InterfaceDefine"
	c.TplName = "interfacedefine/list.html"
}

// Put ...
// @Title Put
// @Description update the Interfacedefine
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Interfacedefine	true		"body for Interfacedefine content"
// @Success 200 {object} models.Interfacedefine
// @Failure 403 :id is not int
// @router /:id [put]
func (c *InterfacedefineController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	v := models.Interfacedefine{Id: id}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if err := models.UpdateInterfacedefineById(&v); err == nil {
			c.Data["json"] = "OK"
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// Delete ...
// @Title Delete
// @Description delete the Interfacedefine
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *InterfacedefineController) Delete() {
	mapp := c.Ctx.Input.Params()
	id, _ := strconv.ParseInt(mapp["1"], 10, 64)
	if err := models.DeleteInterfacedefine(id); err == nil {
		models.ClearInterfacedefineCacheById(id)
		c.ShowMsg("删除成功了",  "/interfacedefine/list.html", 3)
	} else {
		c.ShowMsg("删除失败",  "/interfacedefine/list.html", 3)
	}
}
